package com.baseframe.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.mybatis.utils.PageInfo;
import com.baseframe.mybatis.utils.PageUtil;
import com.baseframe.system.entity.vo.BaseRoleVO;
import com.baseframe.system.feign.BaseSystemFeign;
import com.baseframe.tool.result.R;
import com.baseframe.tool.utils.data.BeanUtil;
import com.baseframe.tool.utils.data.FunUtil;
import com.baseframe.tool.utils.encrypt.Argon2Util;
import com.baseframe.user.entity.BaseUser;
import com.baseframe.user.entity.request.BaseUserRequest;
import com.baseframe.user.entity.vo.BaseUserVO;
import com.baseframe.user.mapper.BaseUserMapper;
import com.baseframe.user.service.BaseUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**

* @description 针对表【base_user(用户表)】的数据库操作Service实现
* @createDate 2023-05-20 19:25:46
*/
@Service
@AllArgsConstructor
@Slf4j
public class BaseUserServiceImpl extends ServiceImpl<BaseUserMapper, BaseUser>
    implements BaseUserService {

    private BaseSystemFeign baseSystemFeign;




    @Override
    public Page<BaseUserVO> getUserPage(Page<BaseUserVO> page, BaseUserRequest request) {

        page =  PageUtil.selectCountPage(page);
        Page<BaseUserVO> pageDto = this.getBaseMapper().getUserPage(page, request);

        pageDto.getRecords().forEach(e->{
            e.setPassword(null);
            e.setGenderName(e.getGender()==0?"女":"男");
            e.setStatusName(e.getStatus()==0?"已封禁":"正常");
        });

        return pageDto;
    }

    @Override
    public boolean sealUser(BaseUserRequest request) {

        return update(new LambdaUpdateWrapper<BaseUser>().eq(BaseUser::getId,request.getId()).set(BaseUser::getStatus,request.getStatus()));
    }

    @Override
    public boolean setRole(BaseUserRequest request) {


        return update(new LambdaUpdateWrapper<BaseUser>().eq(BaseUser::getId,request.getId()).set(BaseUser::getRoleId,request.getRoleId()));
    }

    @Override
    public BaseUserVO getUserInfo(Long userId) {

        return this.getBaseMapper().getUserInfo(userId);
    }

    @Override
    public boolean updateUserinfo(BaseUserRequest request) {
        //修改头像、昵称、性别
        return update(new LambdaUpdateWrapper<BaseUser>()
                .eq(BaseUser::getId,AuthUtil.getUserId())
                .set(FunUtil.isNotEmpty(request.getAvatar()),BaseUser::getAvatar,request.getAvatar())
                .set(FunUtil.isNotEmpty(request.getNickname()),BaseUser::getNickname,request.getNickname())
                .set(FunUtil.isNotEmpty(request.getGender()),BaseUser::getGender,request.getGender())
        );
    }

    @Override
    public boolean bindingEmail(BaseUserRequest request) {



        return update(new LambdaUpdateWrapper<BaseUser>()
                .eq(BaseUser::getId, AuthUtil.getUserId())
                .set(BaseUser::getEmail,request.getNewEmail())

        );
    }

    @Override
    public List<BaseUserVO> searchUser( String searchValue) {


        return getBaseMapper().getUserPage2Front(searchValue);
    }

    @Override
    public R<Object> updatePassword(String newPassword, String oldPassword) {
        Long userId = AuthUtil.getUserId();
        BaseUser baseUser = this.getById(userId);
        String encodedPassword = baseUser.getPassword();
        String prefix2EncodedStr = Argon2Util.possessPrefix2EncodedStr(encodedPassword);

        if (!Argon2Util.matches(prefix2EncodedStr,oldPassword)){

            return R.fail("您输入的旧密码不正确，请重新输入");
        }

        String noPrefixEncodedPassword = Argon2Util.noPrefixEncoded(newPassword);

        return update(new LambdaUpdateWrapper<BaseUser>().eq(BaseUser::getId,userId).set(BaseUser::getPassword,noPrefixEncodedPassword))?R.success():R.fail();
    }

    @Override
    public R<Object> resetPassword(BaseUserRequest request) {

        BaseUser baseUser = this.getOne(new LambdaQueryWrapper<BaseUser>().eq(BaseUser::getUsername,request.getUsername()));

        if (baseUser==null){

            return R.fail(String.format("用户:%s不存在",request.getUsername()));
        }

        if (!baseUser.getEmail().equals(request.getEmail())){

            return R.fail("提供的邮箱与实际邮箱不一致,请检查后重试~");
        }
        //密码加密
        String noPrefixEncoded = Argon2Util.noPrefixEncoded(request.getNewPassword());
        return this.update(new LambdaUpdateWrapper<BaseUser>()
                .eq(BaseUser::getUsername,request.getUsername())
                .set(BaseUser::getPassword,noPrefixEncoded)
        )?R.success():R.fail();
    }

    @Override
    public boolean bindingPhone(BaseUserRequest request) {
        return update(new LambdaUpdateWrapper<BaseUser>()
                .eq(BaseUser::getId, AuthUtil.getUserId())
                .set(BaseUser::getPhone,request.getNewPhone())

        );
    }

    @Override
    public boolean register(BaseUserRequest request) {

        R<BaseRoleVO> roleR = baseSystemFeign.findRoleIdByRoleName("user");
        if(roleR.getData()==null){
            log.warn("角色：[user]不存在~");
            return false;
        }

        Long roleId = roleR.getData().getId();

        BaseUser baseUser = new BaseUser();
        BeanUtils.copyProperties(request,baseUser);
        //加密密码
        String noPrefixEncodedPassword = Argon2Util.noPrefixEncoded(baseUser.getPassword());
        baseUser.setPassword(noPrefixEncodedPassword);
        //设置角色
        baseUser.setRoleId(roleId);
        //设置注册时间、创建人、创建时间、修改人、修改时间
        baseUser.setRegTime(new Date());
        baseUser.setCreateTime(new Date());
        baseUser.setUpdateTime(new Date());
        boolean save = save(baseUser);
        if(!save){
            return false;
        }
        update(new LambdaUpdateWrapper<BaseUser>().eq(BaseUser::getId,baseUser.getId()).set(BaseUser::getCreateBy,baseUser.getId()).set(BaseUser::getUpdateBy,baseUser.getId()));
        return true;

    }


}




